package com.tanhua.bg.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.mongodb.client.result.UpdateResult;
import com.tanhua.bg.enums.CommentType;
import com.tanhua.bg.enums.StateEnum;
import com.tanhua.bg.enums.TopState;
import com.tanhua.bg.mapper.UserInfoMapper;
import com.tanhua.bg.pojo.Comment;
import com.tanhua.bg.pojo.Publish;
import com.tanhua.bg.pojo.PublishAuditing;
import com.tanhua.bg.pojo.UserInfo;
import com.tanhua.bg.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;


import java.util.ArrayList;

import java.util.List;


@Service
@Slf4j
//@Repository
public class MessageService {


    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserInfoMapper userInfoMapper;

    private CommentType commentType;


    //消息拒绝
    public Boolean messageReject(String[] ids) {
        List<ObjectId> list = this.getIds(ids);
        Query query = Query.query(Criteria.where("publishId").in(list));
        Update update = Update.update("state", StateEnum.RGSHJJ.getValue());
        long count = this.mongoTemplate.updateMulti(query, update, PublishAuditing.class).getModifiedCount();
        return count == list.size();
    }

    //消息通过
    public Boolean messagePass(String[] ids) {
        List<ObjectId> list = this.getIds(ids);
        Query query = Query.query(Criteria.where("publishId").in(list));
        Update update = Update.update("state", StateEnum.RGSHTG.getValue());
        long count = this.mongoTemplate.updateMulti(query, update, PublishAuditing.class).getModifiedCount();
        return count == list.size();
    }

    //获取传入的id数组的方法
    private List<ObjectId> getIds(String[] ids){
        List<ObjectId> list = new ArrayList<>();
        for (String id : ids) {
            list.add(new ObjectId(id));
        }
        return list;
    }

    //消息置顶
    public Boolean messageTop(String id) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(id)));
        Update update = Update.update("topState", TopState.ISTOP.getValue());
        long count = this.mongoTemplate.updateMulti(query, update, PublishAuditing.class).getModifiedCount();
        return count > 0;
    }

    //消息取消置顶
    public Boolean messageUnTop(String id) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(id)));
        Update update = Update.update("topState", TopState.NOTTOP.getValue());
        long count = this.mongoTemplate.updateMulti(query, update, PublishAuditing.class).getModifiedCount();
        return count > 0;
    }

    /**
     * 撤销动态
     * @return
     */
    public Boolean revocation(String[] publishIds) {
        String publishId = publishIds[0];


        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId)));
        Update update = Update.update("state",StateEnum.DRGSH.getValue());
        UpdateResult updateResult = this.mongoTemplate.updateFirst(query, update, PublishAuditing.class);
        if (ObjectUtil.isEmpty(updateResult)){
            return false;
        }
        return true;


    }

    /**
     * 动态详情
     * @param publishId
     * @return
     */
    public MessageVo messageInformation(String publishId) {
        //根据发布表的id查询发布表和审核表以及评论表
        //查询发布表
        Query query = new Query(Criteria.where("id").is(publishId));
        Publish publish = this.mongoTemplate.findOne(query, Publish.class);

        //查询审核表
        Query queryAuditing = new Query(Criteria.where("publishId").is(new ObjectId(publishId)));
        PublishAuditing auditing = this.mongoTemplate.findOne(queryAuditing, PublishAuditing.class);

        //查询评论表
        Query queryCommnet = new Query(Criteria.where("publishId").is(new ObjectId(publishId)));
        Comment comment = this.mongoTemplate.findOne(queryCommnet, Comment.class);

        //查询点赞数
        Query queryLikeCount = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(1));
        long likeCount = this.mongoTemplate.count(queryLikeCount,Comment.class);

        //查询评论数
        Query queryCommentCount = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(2));
        long commentCount = this.mongoTemplate.count(queryCommentCount, Comment.class);


        //根据发布表的userId查询userInfo表
        UserInfo userInfo = this.userInfoMapper.selectById(publish.getUserId());

        //判断若有一个为空
        if (!ObjectUtil.isAllNotEmpty(userInfo,publish,auditing,comment)){
            return null;
        }
        //都不为空则进行填充
        MessageVo messageVo = new MessageVo();
        messageVo.setId(auditing.getId().toHexString());
        messageVo.setNickname(userInfo.getNickName());
        messageVo.setUserId(publish.getUserId().intValue());
        messageVo.setUserLogo(userInfo.getLogo());
        messageVo.setCreateDate(publish.getCreated());
        messageVo.setText(publish.getText());

        //填充String[]
        List<String> medias = publish.getMedias();
        String[] strings = new String[medias.size()];
        int i = 0;
        for (String media : medias) {
            strings[i] = media;
            i++;
        }
        messageVo.setMedias(strings);
        messageVo.setTopState(auditing.getTopState());
        messageVo.setState(auditing.getState());
        messageVo.setLikeCount(Convert.toInt(likeCount));
        messageVo.setCommentCount(Convert.toInt(commentCount));
        messageVo.setReportCount(0);
        messageVo.setForwardingCount(0);

        return messageVo;
    }

    /**
     * 消息翻页
     * @param page
     * @param pagesize
     * @param sortProp
     * @param sortOrder
     * @param publishId
     * @param startTime
     * @param endTime
     * @param state
     * @return
     */
    public MsgPageResult queryPage(Integer page, Integer pagesize, String sortProp,
                                   String sortOrder, String publishId, Long startTime, Long endTime, String state) {
        //创建封装返回数据的对象
        MsgPageResult msgPageResult = new MsgPageResult();
        msgPageResult.setPage(page);
        msgPageResult.setPagesize(pagesize);
        //MessageVo的集合
        List<MessageVo> messageVos = new ArrayList<>();

        //queryone:3待审核的     queryFive:5审核通过  queryFour:4审核拒绝  0为查询全部
        //先判断publishid为空
        if (ObjectUtil.isEmpty(publishId)){
            //对类型进行判断
            if (ObjectUtil.equal(state,"all")){
                //查询全部的
                List<PublishAuditing> auditingAll = this.queryAuditing(page,pagesize,sortProp,sortOrder,startTime,
                        endTime,0);
                //进行查询填充
                List<Object> publishIds = CollUtil.getFieldValues(auditingAll, "publishId");
                for (Object id : publishIds) {
                    MessageVo messageVo = this.messageInformation(String.valueOf(id));
                    messageVos.add(messageVo);
                }
                msgPageResult.setCounts(this.queryCount("all", 0));
                msgPageResult.setItems(messageVos);
            }
            else if (ObjectUtil.equal(state,"3")){
                //查询待审核的
                List<PublishAuditing> auditingThrees = this.queryAuditing(page,pagesize,sortProp,sortOrder,startTime,
                        endTime,StateEnum.DRGSH.getValue());
                //进行查询填充
                List<Object> publishIds = CollUtil.getFieldValues(auditingThrees, "publishId");
                for (Object id : publishIds) {
                    MessageVo messageVo = this.messageInformation(String.valueOf(id));
                    messageVos.add(messageVo);
                }
                msgPageResult.setCounts(this.queryCount("state", 3));
                msgPageResult.setItems(messageVos);
            }
            else if (ObjectUtil.equal(state,"4")){
                //查询拒绝的
                List<PublishAuditing> auditingFours = this.queryAuditing(page,pagesize,sortProp,sortOrder,startTime,
                        endTime,StateEnum.RGSHJJ.getValue());
                //进行查询填充
                List<Object> publishIds = CollUtil.getFieldValues(auditingFours, "publishId");
                for (Object id : publishIds) {
                    MessageVo messageVo = this.messageInformation(String.valueOf(id));
                    messageVos.add(messageVo);
                }
                msgPageResult.setCounts(this.queryCount("state", 4));
                msgPageResult.setItems(messageVos);

            }
            else if (ObjectUtil.equal(state,"5")){
                //查询拒绝的
                List<PublishAuditing> auditingFours = this.queryAuditing(page,pagesize,sortProp,sortOrder,startTime,
                        endTime,StateEnum.RGSHTG.getValue());
                //进行查询填充
                List<Object> publishIds = CollUtil.getFieldValues(auditingFours, "publishId");
                for (Object id : publishIds) {
                    MessageVo messageVo = this.messageInformation(String.valueOf(id));
                    messageVos.add(messageVo);
                }
                msgPageResult.setCounts(this.queryCount("state", 5));
                msgPageResult.setItems(messageVos);
            }
        }


    /*    //先判断publishid为空
        if (ObjectUtil.isEmpty(publishId)){
            //填充
            if (ObjectUtil.equal(state,"all") ){
                List<Object> publishIds = CollUtil.getFieldValues(auditingAll, "publishId");
                for (Object id : publishIds) {
                    MessageVo messageVo = this.messageInformation(String.valueOf(id));
                    messageVos.add(messageVo);
                }
                msgPageResult.setCounts(this.queryCount("all", 0));
                msgPageResult.setItems(messageVos);

            }
            else if(ObjectUtil.equal(state,"3")){
                List<Object> publishIds = CollUtil.getFieldValues(auditingOnes, "publishId");
                for (Object id : publishIds) {
                    MessageVo messageVo = this.messageInformation(String.valueOf(id));
                    messageVos.add(messageVo);
                }
                msgPageResult.setCounts(this.queryCount("all", 3));
                msgPageResult.setItems(messageVos);
            }

            else if(ObjectUtil.equal(state,"4")){
                List<Object> publishIds = CollUtil.getFieldValues(auditingFives, "publishId");
                for (Object id : publishIds) {
                    MessageVo messageVo = this.messageInformation(String.valueOf(id));
                    messageVos.add(messageVo);
                }
                msgPageResult.setCounts(this.queryCount("all", 4));
                msgPageResult.setItems(messageVos);
            }


            else if(ObjectUtil.equal(state,"5")){
                List<Object> publishIds = CollUtil.getFieldValues(auditingFours, "publishId");
                for (Object id : publishIds) {
                    MessageVo messageVo = this.messageInformation(String.valueOf(id));
                    messageVos.add(messageVo);
                }
                msgPageResult.setCounts(this.queryCount("all", 5));
                msgPageResult.setItems(messageVos);
            }
        }
*/
        //publishId不为空
        else{

            MessageVo messageVo = this.messageInformation(publishId);
            messageVos.add(messageVo);
            msgPageResult.setCounts(1);
            msgPageResult.setItems(messageVos);

        }

        //获取状态信息
        List<TotalVo> totalVoList = new ArrayList<>();
        //全部
        TotalVo totalVo1 = new TotalVo();
        totalVo1.setTitle("全部");
        totalVo1.setCode("all");
        totalVo1.setValue(this.queryCount("all", 0));
        totalVoList.add(totalVo1);
        //待审核
        TotalVo totalVo2 = new TotalVo();
        totalVo2.setTitle("待审核");
        totalVo2.setCode("3");
        totalVo2.setValue(this.queryCount("state", 3));
        totalVoList.add(totalVo2);
        //已通过
        TotalVo totalVo3 = new TotalVo();
        totalVo3.setTitle("已通过");
        totalVo3.setCode("4");
        totalVo3.setValue(this.queryCount("state", 4));
        totalVoList.add(totalVo3);
        //已驳回
        TotalVo totalVo4 = new TotalVo();
        totalVo4.setTitle("已驳回");
        totalVo4.setCode("5");
        totalVo4.setValue(this.queryCount("state", 5));
        totalVoList.add(totalVo4);

        msgPageResult.setTotals(totalVoList);


        return msgPageResult;
    }



    //查询状态数量的方法
    private Integer queryCount(String colum, Integer code){
        Query query = new Query();
        if ("all".equals(colum)){
            long count = this.mongoTemplate.count(query, PublishAuditing.class);
            return Convert.toInt(count);
        }
        query = Query.query(Criteria.where(colum).is(code));
        long count = this.mongoTemplate.count(query, PublishAuditing.class);
        return Convert.toInt(count);
    }



    /**
     * 查询审核表
     */
    public List<PublishAuditing> queryAuditing(Integer page, Integer pagesize,
                                                String sortProp,String sortOrder, Long startTime, Long endTime ,Integer code){


        //构造条件
        Query query;
        List<PublishAuditing> auditings = new ArrayList<>();
        PageRequest pageRequest;
        //判断升序和降序
        if (sortOrder.equals("descending")){
            pageRequest = PageRequest.of(page - 1,pagesize, Sort.by(Sort.Order.desc(sortProp)));
        }
        else{
            pageRequest = PageRequest.of(page - 1,pagesize, Sort.by(Sort.Order.asc(sortProp)));
        }

        //code为0查询全部
        if (code == 0){
            //判断是否存在起始时间
            //无起始时间,有结束时间
            if (ObjectUtil.isNotEmpty(startTime) && ObjectUtil.isEmpty(endTime)){
                query = new Query(Criteria.where("created").gte(startTime)).with(pageRequest);
            }
            //有起始时间,无结束时间
            else if (ObjectUtil.isEmpty(startTime) && ObjectUtil.isNotEmpty(endTime)){
                query = new Query(Criteria.where("created").lte(endTime)).with(pageRequest);
            }
            //有起始时间和结束时间
            else if (ObjectUtil.isAllNotEmpty(startTime,endTime)){
                query = new Query(Criteria.where("created").gte(startTime)
                        .andOperator(Criteria.where("created").lte(endTime)))
                        .with(pageRequest);
            }
            //无起始时间和结束时间
            else
            {
                query = new Query().with(pageRequest);
            }
            auditings = this.mongoTemplate.find(query, PublishAuditing.class);
        }

        //code不为0
        else{
            //判断是否存在起始时间
            // 无起始时间,有结束时间
            if (ObjectUtil.isNotEmpty(startTime) && ObjectUtil.isEmpty(endTime)){
                query = new Query(Criteria.where("created").gte(startTime)
                        .and("state").is(code)).with(pageRequest);
            }
            //有起始时间,无结束时间
            else if (ObjectUtil.isEmpty(startTime) && ObjectUtil.isNotEmpty(endTime)){
                query = new Query(Criteria.where("created").lte(endTime)
                        .and("state").is(code)).with(pageRequest);
            }
            //有起始时间和结束时间
            else if (ObjectUtil.isAllNotEmpty(startTime,endTime)){
                query = new Query(Criteria.where("created").gte(startTime)
                        .andOperator(Criteria.where("created").lte(endTime)
                                .and("state").is(code))).with(pageRequest);
            }
            //无起始时间和结束时间
            else
            {
                query = new Query(Criteria.where("state").is(code)).with(pageRequest);
            }
            auditings = this.mongoTemplate.find(query, PublishAuditing.class);
        }


        return auditings;
    }





























































    //来自MessageController的评论列表翻页
    public PageResult queryCommentListPage(String token, CommentListQueryParam param) {

        //创建结果对象
        PageResult pageResult = new PageResult();
        pageResult.setPage(param.getPage());
        pageResult.setPagesize(param.getPagesize());

        //获取query请求参数
        Integer page = param.getPage();             //页数
        Integer pageSize = param.getPagesize();     //页尺寸
        String sortProp = param.getSortProp();      //排序字段
        String sortOrder = param.getSortOrder();    //ascending 升序 descending 降序

        PageRequest pageRequest=null;

        //根据id进行排序
        if (StrUtil.equals(sortOrder, "ascending")) {

            pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc("id")));


        }else {
            pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("id")));
        }


        //需要一个查询对象
        Query query = new Query();
        query.with(pageRequest);
        //去mongoDB查评论数据
        List<CommentVo> commentVoList = this.mongoTemplate.find(query, CommentVo.class);

        //把数据集合放入结果对象返回
        pageResult.setItems(commentVoList);
        return pageResult;
    }










}
